<?php
	session_start();
	
	function generateRandomString($length = 10) {
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    $randomString = '';
	    for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, strlen($characters) - 1)];
	    }
	    return $randomString;
	}
	
	if(isset($_POST['email']) && $_POST['email'] != 'E-post')
	{
		try{
			include("sendmail.php");
		
			$email = $_POST['email'];
			
			include 'config.php';

			$resetkey = generateRandomString();
			
			$stmt = $con->prepare('UPDATE `User` SET `ResetKey` =  ? WHERE `Login` = ?');
			$stmt->bind_param('ss', $resetkey, $email);
			$stmt->execute();

			$stmt = $con->prepare('SELECT Name FROM User WHERE Login = ?');
			$stmt->bind_param('s', $email);
			$stmt->execute();
			$result = $stmt->get_result();
			$row = $result->fetch_assoc();
			
		
			
			
			sendNewAccountInfo($email, $row['Name'], $resetkey);

			$_SESSION['message'] = "Kolla din mail och följ instruktionerna för att återställa ditt lösenord.";
			
			mysqli_close($con);
			
			header ("Location: index.php");
		} catch(Exception $e) {
			echo 'Caught exception: ',  $e->getMessage(), "\n";
		}
	}
	else
		header ("Location: index.php");
?>